import {
  Component,
  ViewChild,
  Injector,
  Output,
  EventEmitter
} from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import {
  MaterialChargeServiceProxy,
  MaterialChargeEditDto
} from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';

import * as moment from 'moment';
import { finalize } from 'rxjs/operators';
import { LazyLoadEvent } from 'primeng/primeng';

@Component({
  selector: 'editMaterialModal',
  templateUrl: './edit-material-modal.component.html'
})
export class EditMaterialModalComponent extends AppComponentBase {
  @ViewChild('createOrEditModal') modal: ModalDirective;

  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

  active = false;
  saving = false;
  event: LazyLoadEvent;
  material: MaterialChargeEditDto = new MaterialChargeEditDto();
  baoGuanDate: Date;

  constructor(
    injector: Injector,
    private _materialService: MaterialChargeServiceProxy
  ) {
    super(injector);
  }

  show(id: string, event?: LazyLoadEvent): void {
    this.active = true;
    this.event = event;
    this._materialService.getMaterialChargeForEdit(id).subscribe(result => {
      this.material = result.materialCharge;
      this.baoGuanDate =
        !this.material.baoGuanDate || this.material.baoGuanDate.year() === 1
          ? undefined
          : this.material.baoGuanDate.toDate();
      this.modal.show();
    });
  }

  save(): void {
    this.saving = true;
    this.material.baoGuanDate = moment(this.baoGuanDate).add(8, 'hour');
    this._materialService
      .updateMaterialCharge(this.material)
      .pipe(finalize(() => (this.saving = false)))
      .subscribe(() => {
        this.notify.info(this.l('SavedSuccessfully'));
        this.close();
        this.modalSave.emit(this.event);
      });
  }

  close(): void {
    this.active = false;
    this.modal.hide();
  }
}
